
package com.sl.core.engine.transfer;

import cn.hutool.core.collection.CollUtil;
import com.sl.core.domain.dto.JsonMappingFieldDefine;

import java.util.List;
import java.util.StringJoiner;

public class MappingFiledDefineToJoltDslTransfer {

    public static String transfer(List<JsonMappingFieldDefine> fieldDefineList) {
        if (CollUtil.isEmpty(fieldDefineList)) {
            return "";
        }

        StringJoiner sj = new StringJoiner("\n");
        sj.add("[");
        sj.add("  {");
        sj.add("    'operation': 'shift',");
        sj.add("    'spec': {");

        for (int i = 0; i < fieldDefineList.size(); i++) {
            JsonMappingFieldDefine field = fieldDefineList.get(i);
            String path = field.getMappingPath();

            if (path == null || path.isEmpty()) continue;

            // 使用 mappingPath 去除 $. 后作为 key
            String key = path.replaceFirst("\\$\\.", "");
            String value = field.getFieldCode(); // fieldCode 作为 value

            if (i < fieldDefineList.size() - 1) {
                sj.add(String.format("      '%s': ['%s'],", key, value));
            } else {
                sj.add(String.format("      '%s': ['%s']", key, value));
            }
        }

        sj.add("    }");
        sj.add("  }");
        sj.add("]");

        return sj.toString();
    }
}